/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities;

import greendroid.widget.QuickAction;
import greendroid.widget.QuickActionBar;
import greendroid.widget.QuickActionWidget;
import greendroid.widget.QuickActionWidget.OnQuickActionClickListener;

import java.util.ArrayList;
import java.util.List;

import com.actionbarsherlock.app.SherlockActivity;
import utsc.apps.utschedule.R;
import utsc.apps.utschedule.classes.Assignment;
import utsc.apps.utschedule.classes.Course;
import utsc.apps.utschedule.ui.ExpandableListFragment;
import utsc.apps.utschedule.ui.activities.adapters.AssignmentListAdapter;
import utsc.apps.utschedule.ui.interfaces.TimetableActivity;
import utsc.apps.utschedule.util.database.DatabaseManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.Toast;

/**
 * This is a custom list fragment to display all the {@link utsc.apps.utschedule.classes.Assignment Assignments} for all {@link Course Courses} without tutorials.
 *
 */
public class AssignmentListFragment extends ExpandableListFragment implements android.widget.AdapterView.OnItemLongClickListener,OnQuickActionClickListener {
	
	public static final String TAG="assignmentListFragment";
	public int _timetableID;
	public static final String ARGS_TIMETABLEID="timetableID";
	public List<Course> _courseList;
	public AssignmentListAdapter _adapter;
	private boolean _updated;
	private QuickActionWidget _quickAction;
	private int _selectedGrpPos=-1;
	private int _selectedChldPos=-1;
	/**
	 * This is used to store the result course id from detail view, so we can refresh the list accordingly.
	 */
	private int _resultCourseID;
	/**
	 * The empty constructor is required.
	 */
	public  AssignmentListFragment() {
	}

	/**
	 * This is the recommended way to create a new fragment. It takes in a timetable id as an argument.
	 * @param timetableID
	 * @return
	 */
	public static AssignmentListFragment newInstance(int timetableID){
		Bundle args=new Bundle();
		args.putInt(ARGS_TIMETABLEID, timetableID);
		AssignmentListFragment fragment=new AssignmentListFragment();
		fragment.setArguments(args);
		return fragment;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		_quickAction=new QuickActionBar(getSherlockActivity());
		QuickAction _editAction=new QuickAction(getSherlockActivity(), R.drawable.ic_action_edit_alt, "Edit");
		QuickAction _deleteAction=new QuickAction(getSherlockActivity(), R.drawable.ic_action_delete_alt, "Delete");
		_quickAction.addQuickAction(_editAction);
		_quickAction.addQuickAction(_deleteAction);
		_quickAction.setOnQuickActionClickListener(this);
		//move the group indicator from the left to right
		DisplayMetrics metrics = new DisplayMetrics();
	        getSherlockActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
	        int width = metrics.widthPixels;
		ExpandableListView listView=getExpandableListView();
		listView.setCacheColorHint(Color.TRANSPARENT);
		listView.setGroupIndicator(getResources().getDrawable(R.drawable.list_group_indicator));
		listView.setIndicatorBounds(width-60, width);
		listView.setOnItemLongClickListener(this);
		Bundle args=getArguments();
		if (args!=null) {
			_timetableID=args.getInt(ARGS_TIMETABLEID);
		}
		//setup the underlying listview
		onContentChanged();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode==SherlockActivity.RESULT_OK) {
			_updated=false;
			_resultCourseID=data.getIntExtra("AssignmentCourseForResult",0);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		//setup the list adapter if this is the first time open
		if (_courseList==null) {
			_courseList=DatabaseManager.getInstance(getSherlockActivity()).getCoursesWithoutTutorials(_timetableID);
			_adapter=new AssignmentListAdapter(_courseList, getSherlockActivity());
			if (_courseList==null || _courseList.isEmpty()) {
				setEmptyText("No Courses Found!");
			}
			setListAdapter(_adapter);
		}
		//otherwise, just update the adapter
		else {
			_courseList=DatabaseManager.getInstance(getSherlockActivity()).getCoursesWithoutTutorials(_timetableID);
			_adapter.set_courses(new ArrayList<Course>(_courseList));
		}
	}
	
	public void setListAdapter(AssignmentListAdapter adapter) {
		super.setListAdapter(adapter);
	}
	
	@Override
	public AssignmentListAdapter getExpandableListAdapter() {
		return (AssignmentListAdapter) super.getExpandableListAdapter();
	}
	
	@Override
	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
		
		Assignment child=getExpandableListAdapter().getChild(groupPosition, childPosition);
		//checks if the "new assignment" button was clicked
		if (child==null) {
			//simply open the new assignment form
			Intent newAssignmentIntent=new Intent(getSherlockActivity(), AssignmentFormActivity.class);
			newAssignmentIntent.putExtra("CourseAssignment", getExpandableListAdapter().getGroup(groupPosition).get_courseID());
			newAssignmentIntent.putExtra("RequestCode", TimetableActivity.RESULT_NEW_ASSIGNMENT);
			startActivityForResult((newAssignmentIntent),TimetableActivity.RESULT_NEW_ASSIGNMENT);
		}else {
			//otherwise, open the assignment form with the assignment data
			Intent updateAssignmentIntent=null;
			updateAssignmentIntent=new Intent(getSherlockActivity(),AssignmentDetailActivity.class);
			updateAssignmentIntent.putExtra(Assignment.EXPIRED, child.is_expired());
			updateAssignmentIntent.putExtra(Assignment.COURSE, child.get_course().get_courseID());
			updateAssignmentIntent.putExtra(Assignment.ASSUID, child.get_AssUID());
			startActivityForResult(updateAssignmentIntent, TimetableActivity.RESULT_UPDATE_ASSIGNMENT);
		}
		
		return true;
	}


	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View view, int arg2,
			long id) {
		if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
            _selectedGrpPos = ExpandableListView.getPackedPositionGroup(id);
            _selectedChldPos = ExpandableListView.getPackedPositionChild(id);
            Assignment child=getExpandableListAdapter().getChild(_selectedGrpPos, _selectedChldPos);
            //show the quick action
            if (child!=null) {
            	_quickAction.show(view);
			}
            // Return true as we are handling the event.
            return true;
        }
		
		return false;
	}

	@Override
	public void onQuickActionClicked(QuickActionWidget widget, int position) {
		Assignment selectedAssignment=getExpandableListAdapter().getChild(_selectedGrpPos, _selectedChldPos);
		//only perform the quick action if the attached item is a valid assignment object
		if (selectedAssignment!=null) {
			//the first quick action is edit
			if (position==0) {
					Intent updateAssignmentIntent=selectedAssignment.getObjectIntent();
	            	updateAssignmentIntent.setClass(getSherlockActivity(), AssignmentFormActivity.class);
	    			updateAssignmentIntent.putExtra("CourseAssignment", selectedAssignment.get_course().get_courseID());
	    			updateAssignmentIntent.putExtra("RequestCode", TimetableActivity.RESULT_UPDATE_ASSIGNMENT);
	    			startActivityForResult(updateAssignmentIntent, TimetableActivity.RESULT_UPDATE_ASSIGNMENT);
			}
			//the second quick action is delete
			else {
				DatabaseManager.getInstance(getSherlockActivity()).deleteAssignmentById(selectedAssignment.get_AssUID());
				_resultCourseID=selectedAssignment.get_course().get_courseID();
				_adapter.notifyDataSetChanged(_resultCourseID);
				Toast.makeText(getSherlockActivity(), selectedAssignment.get_Title()+" is deleted.", Toast.LENGTH_SHORT).show();
			}
		}
		widget.dismiss();
	}
	
}
